import React, { useState, useEffect, useRef } from 'react';
import { Box, Button, Dialog, Divider, Loading, Message, Tab } from '@alifd/next';
import { observer } from 'mobx-react-lite';
import html2canvas from 'html2canvas';
import styles from './QR.module.scss';
import { useStore } from '@/hooks';
import { t } from '@lingui/macro';

interface QRProps {
  name: string; // 二维码描述文字
  open: boolean; // 打开关闭modal
  onCancel: () => void; // 关闭modal事件
  describe?: string; // 底部文字描述
  baseUrl: string; // url核心链接
  okText?: string; // 自定义确定按钮文字
  cancelText?: string; // 自定义取消按钮文字
  id: string;
  modalStyle?: React.CSSProperties; // modal自定义样式
}

interface AsyncFuncProps {
  getURL: (id: string, scene: number, key: string) => Promise<string>;
  getCommandCode: (scene: number, activityId: string, path: string) => Promise<CommandCodeProps>;
}

interface CommandCodeProps {
  result: string;
}

class CodeUrl {
  private modal: QRProps;
  private setLoading: (loading: boolean) => void;
  private setUrl: (url: string) => void;
  private setCode: (code: string) => void;
  private store: AsyncFuncProps;

  constructor(
    modal: QRProps,
    setLoading: (loading: boolean) => void,
    setUrl: (url: string) => void,
    setCode: (code: string) => void,
    store: AsyncFuncProps,
  ) {
    this.modal = modal;
    this.setLoading = setLoading;
    this.setUrl = setUrl;
    this.setCode = setCode;
    this.store = store;
  }

  async fetch(scene: number, key: string) {
    const { getURL, getCommandCode } = this.store;
    const { id } = this.modal;
    this.setLoading(true);
    try {
      const baseUrl: string = await getURL(id, scene, key);
      const commandCode: CommandCodeProps = await getCommandCode(scene, id, key)
      this.setCode(commandCode?.result);
      this.setUrl(baseUrl);
    } catch (error) {
      console.error('🚀 _ file: index.tsx:45 _ CodeUrl _ error:', error);
      throw error;
    } finally {
      this.setLoading(false);
    }
  }

  static create(
    modal: QRProps,
    setLoading: (loading: boolean) => void,
    setUrl: (url: string) => void,
    setCode: (code: string) => void,
    store: AsyncFuncProps,
  ) {
    return new CodeUrl(modal, setLoading, setUrl, setCode, store);
  }
}

export default observer(function ({ modal, ...props }: { modal: QRProps }, ...any) {
  const [url, setUrl] = useState('');
  const [loading, setLoading] = useState(false);
  const { activityStore: store } = useStore();
  const divRef = useRef<HTMLDivElement | null>(null);
  const [key, setKey] = useState('1');
  const [code, setCode] = useState('');
  const CodeUrlfetcher = CodeUrl.create(modal, setLoading, setUrl, setCode, store);

  useEffect(() => {
    if (modal.open) {
      (async () => {
        await CodeUrlfetcher.fetch(1000, '1');
      })();
    }
    return () => {
      setKey('1');
    };
  }, [modal]);

  const cancelHandle = () => {
    modal.onCancel();
  };

  const downloadCode = () => {
    setTimeout(() => {
      if (divRef.current) {
        html2canvas(divRef.current, { useCORS: true }).then((canvas) => {
          const link = document.createElement('a');
          link.href = canvas.toDataURL('image/png');
          link.download = `${modal.name}专属二维码.png`;
          link.click();
          modal.onCancel();
        });
      }
    }, 500);
  };

  const handleOnChangeTab = async (v: string) => {
    setKey(v);
    switch (v) {
      case '1':
        await CodeUrlfetcher.fetch(1000, v);
        break;
      case '2':
        // 跳转到公众号
        await CodeUrlfetcher.fetch(1001, v);
        const text = `pages/sub/activity?activityId=${modal.id}&scene=activity:1001`;
        setUrl(text);
        break;
      case '3':
        // 跳转到微信朋友圈
        await CodeUrlfetcher.fetch(1002, v);
        break;
      case '4':
        // 跳转到小红书01
        await CodeUrlfetcher.fetch(1003, v);
        break;
      case '5':
        // 跳转到小红书02
        await CodeUrlfetcher.fetch(1005, v);
        break;
      case '6':
        // 跳转到海报
        await CodeUrlfetcher.fetch(1004, v);
        break;
      default:
        break;
    }
  };

  const handleClickAndCopy = async (e) => {
    try {
      await navigator.clipboard.writeText(url);
      Message.success({ content: t`已复制！` });
    } catch (err) {
      console.error('文本复制失败: ', err);
    }
  };

  const handleClickCodeCopy = async () => {
    try {
      await navigator.clipboard.writeText(code);
      Message.success({ content: t`已复制！` });
    } catch (err) {
      console.error('文本复制失败: ', err);
    }
  };

  return (
    <>
      <Dialog
        v2
        title={`【${modal.name}】专属二维码`}
        visible={modal.open}
        style={{ width: 500, ...modal.modalStyle }}
        onOk={downloadCode}
        okProps={{ children: modal.okText }}
        onClose={cancelHandle}
        cancelProps={{ children: modal.cancelText }}
      >
        <Tab defaultActiveKey="1" activeKey={key} onChange={handleOnChangeTab}>
          <Tab.Item disabled={loading} key={'1'} title={t`小程序主页`} />
          <Tab.Item disabled={loading} key={'2'} title={t`微信公众号`} />
          <Tab.Item disabled={loading} key={'3'} title={t`微信朋友圈`} />
          <Tab.Item disabled={loading} key={'4'} title={t`小红书01`} />
          <Tab.Item disabled={loading} key={'5'} title={t`小红书02`} />
          <Tab.Item disabled={loading} key={'6'} title={t`海报活动页`} />
        </Tab>
        <Loading visible={loading} style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
          <div
            // 使用非空断言运算符 ! 来告诉 TypeScript 你确定 ref 不会为 null
            ref={divRef!}
            id="qrcode-container"
            className={styles.qr_container}
          >
            <div className={styles.qr_content}>
              {key == '2' ? (
                <div
                  style={{
                    width: '50%',
                    display: 'flex',
                    flexWrap: 'wrap',
                    justifyContent: 'center',
                    alignItems: 'center',
                  }}
                >
                  <span>{t`公众号参数：`}</span>
                  <span style={{ whiteSpace: 'pre-line', display: 'block' }}>{url}</span>
                  <Button
                    text
                    style={{ marginLeft: 10 }}
                    onClick={handleClickAndCopy}
                    type="primary"
                  >{t`点击复制`}</Button>
                </div>
              ) : (
                <img src={url} style={{ width: '60%' }} alt="这是一个二维码" />
              )}

              <div style={{ marginTop: 20 }} className={styles.qr_content_name}>
                {modal.name}
              </div>

              {/* 指令代码 */}
              <div>{modal?.describe || '三地通跨境出行服务平台'}</div>
              <Divider />
              <Box wrap direction="row" justify="center" align="center">
                <div>{t`指令代码：${code}`}</div>
                <Button text type="primary" style={{ marginLeft: 5 }} onClick={handleClickCodeCopy}>{t`复制`}</Button>
              </Box>
            </div>
          </div>
        </Loading>
      </Dialog>
    </>
  );
});
